package com.iflytek.uoamp.agent.monitor.version;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;

import org.apache.log4j.Logger;

import com.iflytek.uoamp.agent.common.util.Sign;
import com.iflytek.uoamp.agent.common.util.WFile;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.NewVersion;
import com.iflytek.uoamp.agent.monitor.find.CMDExextor;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentConfig;

public class Version {
	private Map<String, String> headers;
	private byte[] body;

	public Version(){
		
	}
	
//	public Version(Base64Version version){
//		this.headers = version.getHeaders();
//		this.body = version.getBodyByBase64();
//	}
	
	public Version(NewVersion version){
		this.headers = version.getHeaders();
		this.body = version.exchangeBodyToByte(); 
	}
	
	
	public Map<String, String> getHeaders() {
		return headers;
	}
	public void setHeaders(Map<String, String> headers) {
		this.headers = headers;
	}
	public byte[] getBody() {
		return Arrays.copyOf(body, body.length);
	}

	public void setBody(byte[] body) {
		this.body = Arrays.copyOf(body, body.length);
	}
	
	public boolean save(){
		
		String type = headers.get("type");
		if(type==null || type.equals("txt") || type.equals("find")){
			String path = headers.get("path");
			String md5 = headers.get("md5");
			Logger.getRootLogger().info("try write "+path);
			path = path.replaceAll("\\\\", "/");
			
			String clientMd5= Sign.byteToString(Sign.getSign(body));
			if(md5!=null && clientMd5!=null){
				if(md5.equals(clientMd5)){
					WFile.wfByByte(path, body);
					if (MCAgentConfig.getInstance().isLinux()) {
						CMDExextor.execut("chmod 700 -R "+path);
					}
					return true;
				}else{
					Logger.getRootLogger().error("sign is not equal,so cant update!");
				}
			}else{
				WFile.wfByByte(path, body);
				if (MCAgentConfig.getInstance().isLinux()) {
					CMDExextor.execut("chmod 700 -R "+path);
				}
				return true;
			}
		}else if(type.equals("version")){
			MCAgentConfig.getInstance().setVersion(new String(body));
			WFile.wf("conf/version", MCAgentConfig.getInstance().getSubVersion(),"utf-8",false);
			return true;
		}
		return false;
	}

}
